package com.springboot.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.springboot.mall.common.Result;
import com.springboot.mall.entity.User;
import com.springboot.mall.service.UserService;
import com.springboot.mall.utils.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    /**
     * 发送手机验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        //生成随机的4为验证码
        if (StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //调用阿里云提供的短信服务API完成短信发送
            //SMSUtils.sendMessage("","",phone, code);
            //将生成的验证码保存到Session
            //session.setAttribute(phone,code);

            //将生成的验证码存到redis中（优化）
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            System.out.println(code);

            return Result.success("手机验证码发送成功");
        }
        return Result.error("短信发送失败");
    }

    /**
     * 用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody Map map,HttpSession session){

        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从Session中获取生成的验证码
        //String codeInSession = session.getAttribute(phone).toString();

        //从redis中获取验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);

        //进行验证码的比较
        if (code != null && code.equals(codeInSession)){
            //验证码一致，成功登录
            //判断当前手机号是否注册，自动完成注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if (user == null){
                user = new User();
                user.setPhone(phone);
                //随机生成姓名
                String chars = "abcdefghijklmnopqrstuvwxyz";
                char name = chars.charAt((int) (Math.random() * 26));
                user.setName(name+phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            //登录成功，删除redis中缓存的验证码
            redisTemplate.delete(phone);

            return Result.success(user);
        }
        return Result.error("验证码错误");
    }

    /**
     * 用户退出登录
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public Result<String> logout(HttpServletRequest request){
        //清除Session中保存的当前登录用户的id
        request.getSession().removeAttribute("user");
        return Result.success("退出成功！！！");
    }

}
